package com.swallow.cloud.common.utils;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Author: L.swallow
 * @Date: 2018/12/29 17:03
 */
public class PropertiesUtil {

    public static final String[] DEFAULT_CONFIG_FILE = new String[]{
            "classpath:core.yml",
            "classpath:application.yml"};

    private final Properties properties = new Properties();


    static {
        releadInstance();
    }

    public PropertiesUtil(String... configFiles) {
        for (String location : configFiles) {
            try {
                Resource resource =  new DefaultResourceLoader().getResource(location);
                if (resource.exists()){
                        YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
                        bean.setResources(resource);
                        for (Map.Entry<Object,Object> entry : bean.getObject().entrySet()){
                            properties.put(entry.getKey().toString(),  entry.getValue().toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static PropertiesUtil releadInstance(){
        Set<String> configFiles =new LinkedHashSet<>();
        for (String configFile : DEFAULT_CONFIG_FILE){
            configFiles.add(configFile);
        }
        return new PropertiesUtil(configFiles.toArray(new String[configFiles.size()]));
    }

    /**
     * 当前类实例
     */
    public static PropertiesUtil getInstance(){
        return releadInstance();
    }
    public  Properties getProperties(){
        return releadInstance().properties;
    }

}
